import java.util.*
import java.text.*

if (args.length < 3) {
    println "Usage: groovy "+getClass().getName()+" [metadata-root-path] [removed-packages-file] [log-file]"
    println "Example: groovy "+getClass().getName()+" ~/mephisto/data/cooker/i586-main-release/ ~/mephisto/data/cooker/i586-main-release.removed.list ~/logs/mphs.log"
    return
}

mphsRoot = args[0]
removedFile = args[1]
log = new File(args[2])

removed = new File(removedFile)
oldfiles = removed.getText().split()
log.append("\n== Removing diff package metadata ==\n")
sdf = new SimpleDateFormat("yyyyddMM-HHmm")
now = sdf.format(new Date())


failed = new ArrayList()
succeeded = new ArrayList()

for (file in oldfiles) {
     toBeRemoved = new File("$mphsRoot/"+file)
     print "Deleting ${toBeRemoved}..."
     log.append("${now} - Deleting ${toBeRemoved} - \n")
     result = deleteDir(toBeRemoved)
     if (result)
        succeeded.add(file)
     else
        failed.add(file)
     
     
     println " ${result}."
}
 
 println("Succeeded: "+succeeded.size())
 println("Failed: "+failed.size())
 log.append("Succeeded: "+succeeded.size()+" - Failed: "+failed.size()+": "+failed+"\n")

 boolean deleteDir(final File self) {
        if (!self.exists())
            return true;
        if (!self.isDirectory())
            return false;

        File[] files = self.listFiles();
        if (files == null)
            // couldn't access files
            return false;

        // delete contained files
        boolean result = true;
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            if (file.isDirectory()) {
                if(!deleteDir(file))
                    result = false;
            }
            else {
                if (!file.delete())
                    result = false;
            }
        }

        // now delete directory itself
        if(!self.delete())
            result = false;

        return result;
    }
 